{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<style>div.container { width: 100% }</style>\n",
    "<img style=\"float:left;  vertical-align:text-bottom;\" height=\"65\" width=\"172\" src=\"../assets/PyViz_logo_wm_line.png\" />\n",
    "<div style=\"float:right; vertical-align:text-bottom;\"><h2>Tutorial 10. Working with large datasets</h2></div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "HoloViews supports even high-dimensional datasets easily, and the standard mechanisms discussed already work well as long as you select a small enough subset of the data to display at any one time.  However, some datasets are just inherently large, even for a single frame of data, and cannot safely be transferred for display in any standard web browser. Luckily, HoloViews makes it simple for you to use the separate [Datashader](http://datashader.readthedocs.io) library together with any of the plotting extension libraries, including Bokeh and Matplotlib. Datashader is designed to complement standard plotting libraries by providing faithful visualizations for very large datasets, focusing on revealing the overall distribution, not just individual data points.\n",
    "\n",
    "Datashader uses computations accelerated using [Numba](http://numba.pydata.org), making it fast to work with datasets of millions or billions of datapoints stored in [Dask](http://dask.pydata.org/en/latest/) dataframes.  Dask dataframes provide an API that is functionally equivalent to Pandas, but allows working with data out of core and scaling out to many processors across compute clusters. Here we will use Dask to load a large Parquet-format file of taxi coordinates.\n",
    "\n",
    "<div style=\"margin: 10px\">\n",
    "<a href=\"http://holoviews.org\"><img style=\"margin:8px; display:inline; object-fit:scale-down; max-height:150px\" src=\"../assets/holoviews.png\"/></a>\n",
    "<a href=\"http://geoviews.org\"><img style=\"margin:8px; display:inline; object-fit:scale-down; max-height:150px\" src=\"../assets/geoviews.png\"/></a>\n",
    "<a href=\"http://bokeh.pydata.org\"><img style=\"margin:8px; display:inline; object-fit:scale-down; max-height:150px\" src=\"../assets/bokeh.png\"/></a>\n",
    "<a href=\"http://datashader.org\"><img style=\"margin:8px; display:inline; object-fit:scale-down; max-height:150px\" src=\"../assets/datashader.png\"/></a><br><br>\n",
    "<a href=\"http://pandas.pydata.org\"><img style=\"margin:8px; display:inline; object-fit:scale-down; max-height:140px\" src=\"../assets/pandas.png\"/></a>\n",
    "<a href=\"http://numba.pydata.org\"><img style=\"margin:8px; display:inline; object-fit:scale-down; max-height:150px\" src=\"../assets/numba.png\"/></a>\n",
    "<a href=\"http://dask.pydata.org\"><img style=\"margin:8px; display:inline; object-fit:scale-down; max-height:140px\" src=\"../assets/dask.png\"/></a>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### How does datashader work?\n",
    "\n",
    "<img src=\"../assets/datashader_pipeline.png\" width=\"80%\"/>\n",
    "\n",
    "* Tools like Bokeh map **Data** (left) directly into an HTML/JavaScript **Plot** (right)\n",
    "* datashader instead renders **Data** into a plot-sized **Aggregate** array, from which an **Image** can be constructed then embedded into a Bokeh **Plot**\n",
    "* Only the fixed-sized **Image** needs to be sent to the browser, allowing millions or billions of datapoints to be used\n",
    "* Every step automatically adjusts to the data, but can be customized"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### When not to use datashader\n",
    "\n",
    "* Plotting less than 1e5 or 1e6 data points\n",
    "* When every datapoint must be resolveable individually; standard Bokeh will render all of them\n",
    "* For full interactivity (hover tools) with every datapoint\n",
    "\n",
    "#### When to use datashader\n",
    "\n",
    "* Actual big data; when Bokeh/Matplotlib have trouble\n",
    "* When the distribution matters more than individual points\n",
    "* When you find yourself sampling, decimating, or binning to better understand the distribution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import holoviews as hv\n",
    "import dask.dataframe as dd\n",
    "import datashader as ds\n",
    "import geoviews as gv\n",
    "\n",
    "from holoviews.operation.datashader import datashade, rasterize\n",
    "hv.extension('bokeh')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load the data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As a first step we will load a large dataset using Dask. If you have followed the setup instructions you will have downloaded a large Parquet-format file containing 12 million taxi trips.  Let's load this data using dask to create a dataframe ``ddf``:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-warning\" role=\"alert\">\n",
    "  If you are low on memory (less than 8 GB) or have not downloaded the full data, you can load only a subset of the data by changing 'data/' to 'data/.data_stubs/'.</code>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ddf = dd.read_parquet('../data/nyc_taxi_wide.parq').persist()\n",
    "\n",
    "print('%s Rows' % len(ddf))\n",
    "print('Columns:', list(ddf.columns))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create a dataset\n",
    "\n",
    "In previous sections we have already seen how to declare a set of [``Points``](http://holoviews.org/reference/elements/bokeh/Points.html) from a pandas dataframe. Here we do the same for a Dask dataframe passed in with the desired key dimensions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "points = hv.Points(ddf, kdims=['dropoff_x', 'dropoff_y'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We could now simply type ``points``, and Bokeh would attempt to display this data as a standard Bokeh plot. Before doing that, however, remember that we have 12 million rows of data, and no current plotting program will handle that well in a web browser! Instead of letting Bokeh see this data, let's convert it to something far more tractable using the ``datashade`` operation. This operation will aggregate the data on a 2D grid, apply shading to assign pixel colors to each bin in this grid, and build an ``RGB`` Element (just a fixed-sized image) we can safely display in a browser:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%opts RGB [width=600 height=500 bgcolor=\"black\"]\n",
    "datashade(points)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you zoom in you will note that the plot rerenders depending on the zoom level, which allows the full dataset to be explored interactively even though only an image of it is ever sent to the browser.  The way this works is that ``datashade`` is a dynamic operation that also declares some linked streams. These linked streams are automatically instantiated and dynamically supply the ``plot_size``, ``x_range``, and ``y_range`` from the Bokeh plot to the operation based on your current viewport as you zoom or pan:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "datashade.streams"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Exercise: Plot the taxi pickup locations ('pickup_x' and 'pickup_y' columns)\n",
    "# Warning: Don't try to display hv.Points() directly; it's too big! Use datashade() or rasterize() for any display\n",
    "# Optional: Change the cmap on the datashade operation to inferno\n",
    "\n",
    "from datashader.colors import inferno\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Adding a tile source\n",
    "\n",
    "Using the GeoViews (geographic) extension for HoloViews, we can display a map in the background. Just declare a Bokeh WMTSTileSource and pass it to the gv.WMTS Element, then we can overlay it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%opts RGB [xaxis=None yaxis=None]\n",
    "from bokeh.models import WMTSTileSource\n",
    "url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg'\n",
    "wmts = WMTSTileSource(url=url)\n",
    "gv.WMTS(wmts) * datashade(points)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Exercise: Overlay the taxi pickup data on top of the Wikipedia tile source\n",
    "\n",
    "wiki_url = 'https://maps.wikimedia.org/osm-intl/{Z}/{X}/{Y}@2x.png'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Aggregating with a variable"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So far we have simply been counting taxi dropoffs, but our dataset is much richer than that. We have information about a number of variables including the base cost of a taxi ride, the ``fare_amount``. Datashader provides a number of ``aggregator`` functions, which you can supply to the datashade operation. Here use the ``ds.mean`` aggregator to compute the average cost of a trip at a dropoff location:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "selected = points.select(fare_amount=(None, 1000))\n",
    "selected.data = selected.data.persist()\n",
    "gv.WMTS(wmts) * datashade(selected, aggregator=ds.mean('fare_amount'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Exercise: Use the ds.min or ds.max aggregator to visualize  ``tip_amount``  by dropoff location\n",
    "# Optional: Eliminate outliers by using select\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Grouping by a variable\n",
    "\n",
    "Because datashading happens only just before visualization, you can use any of the techniques shown in previous sections to select, filter, or group your data before visualizing it, such as grouping it by the hour of day:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%opts Image [width=600 height=500 logz=True xaxis=None yaxis=None tools=['hover'] colorbar=True]\n",
    "taxi_ds = hv.Dataset(ddf)\n",
    "grouped = taxi_ds.to(hv.Points, ['dropoff_x', 'dropoff_y'], groupby=['dropoff_hour'], dynamic=True)\n",
    "rasterize(grouped).redim.values(dropoff_hour=range(24))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we're using `rasterize()`, which is the same as `datashade()` except that instead of using datashader to map the counts per pixel into a color for that pixel, it's letting Bokeh do that mapping, in your local browser. Although letting Bokeh do the colormapping means that we can't use datashader-specific features such as the default `eq_hist` histogram normalization, it does mean that we can use Bokeh's features like colorbars and hover support.  Here, if you hover over a given pixel, it will tell you the count of trips that fall into that pixel, along with the location in Web Mercator coordinates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Exercise: Facet the trips in the morning hours as an NdLayout using rasterize(grouped.layout())\n",
    "# Hint: You can reuse the existing grouped variable or select a subset before using the .to method\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As you can see, datashader requires taking some extra steps into consideration, but it makes it practical to work with even quite large datasets on an ordinary laptop.  On a 16GB machine, datasets 10X or 100X the one used here should be very practical, as illustrated at the [datashader web site](https://datashader.org).\n",
    "\n",
    "\n",
    "# Onwards\n",
    "\n",
    "* The [HoloViews Large Data](http://holoviews.org/user_guide/Large_Data.html) user guide explains in more detail how to work with large datasets using datashader.\n",
    "* HoloViews also contains a [sample bokeh app](http://holoviews.org/gallery/apps/bokeh/nytaxi_hover.html) using this dataset and an additional linked stream that works well as a starting point.\n",
    "\n",
    "Next, we go on to show how to create [live plots of dynamically updated data](./11_Streaming_Data.ipynb) (i.e. streaming data)."
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
